import React, { Component } from 'react';
import {
	StyleSheet, Text, View, TouchableOpacity,
	KeyboardAvoidingView, Image, ScrollView, PixelRatio, Platform, Alert
} from "react-native";
import { API, API_GENERATE } from '../../../../config/api';
import { GLOBAL } from '../../../../config/global';
import { style } from '../../../../theme/style';
import { Common } from '../../../../component/common/Common';
import { FormItem } from '../component/FormItem';
import moment from 'moment';
import DatePicker from 'react-native-datepicker';
import { PageStatusIndex } from '../../../../component/page-status/PageStatusIndex';
import HTTP from '../../../../utils/http';
import Dictionary from '../../../../utils/dictionary';
import ToastUtil from '../../../../utils/toast';
import MethodUtil from '../../../../utils/MethodUtil';
const scale = GLOBAL.SCALE;
import { CURRENCY } from '../../../../utils/helper';
import { STORAGE_CONSTANT } from '../../../../config/storage';
import StorageHelper from '../../../../utils/storageHelper';
// 1 供应商   2. 客户  
//let corpTypeList = ['1', '2'];

export class CreditFormPage extends Component {
	static navigationOptions = ({ navigation, navigationOptions }) => {
		return {
			headerTitle: '申请授信',
			headerTintColor: style.color.white,
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
			headerRight: (<Image style={{ marginLeft: 18 * scale, width: 9 * scale, height: 16 * scale }} source={require('../../../../imgs/goBackEmpty.png')} />),
			headerStyle: style.head.headerStyle,
			headerTitleStyle: {
				flex: 1,
				textAlign: 'center',
			}
		}
	};

	constructor(props) {
		super(props);
		let { companyId, orderType, echoData, choice } = props.navigation.state.params;
		console.log('props.navigation.state.params', props.navigation.state.params)
		this.echoData = echoData;
		this.choice = choice || {}; //业务组织

		// 万元转换
		if (echoData && echoData.zxbApproveAmount) {
			echoData.zxbApproveAmount = MethodUtil.countObj.divide(echoData.zxbApproveAmount, 10000).toString() || '0';
		}
		if (echoData && echoData.creditApplyAmount) {
			echoData.creditApplyAmount = MethodUtil.countObj.divide(echoData.creditApplyAmount, 10000).toString() || '0';
		}

		this.companyId = echoData ? echoData.companyId : companyId;
		this.orderType = orderType;

		this.state = {
			loadPage: true,
			loadStatus: 'loading'
		}
		this.data = {
			// 额度详情数据
			limitDetailData: {},
			// 授信类型
			typeModal: false,
			typeData: [],
			typeValue: '请选择',
			typeIndex: -1,
			// 常用结算方式
			accountModal: false,
			accountData: [],
			accountValue: '请选择',
			accountIndex: -1,
			lsAccountData: [],  // 临时存储数字字典数据

			// 申请参数
			sendData: this.echoData || {
				creditType: 1,
				accountDay: '5'  // 默认5天
			},
		}
		this.requesting = false;
	}

	async	componentWillMount() {

		if (!this.choice.corpId) {
			this.choice.corpId = await this._getUserInfo();
		}
		this._fieldInit();  // 字段初始化
		await this._getCompanyData();  // 企业信息初始化
		this.data.lsAccountData = await Dictionary.get('EC_PAY_TYPE');  //结算价 数据类型
		await this._accountsInit();  // 
	}

	componentWillUnmount() {

	}

	//获取用户信息
	_getUserInfo = async () => {
		//获取用户信息
		let userInfo = await StorageHelper.get(STORAGE_CONSTANT.USER_INFO_KEY);
		if (userInfo) {
			this.userInfo = JSON.parse(userInfo);
		}
		return this.userInfo.corpId || null;
	}

	// 企业信息
	_getCompanyData = async () => {
		const responseData = await HTTP.POST(API_GENERATE(API.GET_CUSTOMER_DETAIL), {
			companyId: this.companyId,
			corpId: this.choice.corpId
		});
		if (responseData) {
			let { companyName, companyId, createTime, corpTypeList, registerFund, registerFundCurrency } = responseData.companyInfoVO;

			if (corpTypeList.length) {
				this.data.sendData.corpTypeList = corpTypeList;
			} else {
				this.data.sendData.corpTypeList = ['1', '2'];
			}
			if (this.orderType) {
				this.orderType = this.orderType == 'S' ? '2' : '1';
				this.data.sendData.corpTypeList.forEach((item, index) => {
					if (this.orderType != item) {
						this.data.sendData.corpTypeList.splice(index, 1)
					}
				});
			}

			this.data.sendData.companyId = companyId;
			this.data.companyName = companyName;
			this.data.registerFund = registerFund;
			this.data.registerFundCurrency = registerFundCurrency;
			this.data.createTime = createTime.split(' ')[0];  //时间去掉秒;
		}
	}


	//授信额度数据
	_detailFn = async () => {
		let saveData = await HTTP.POST(API_GENERATE(API.CREDIT_LIMIT_DETAIL), {
			companyId: this.data.sendData.companyId,
			creditKind: this.data.sendData.creditKind,
			corpId: this.choice.corpId
		});
		if (saveData) {
			this.data.limitDetailData = saveData;
			this.setState({
				loadPage: false
			})
		}
	}

	//字段初始化
	_fieldInit = () => {
		let { sendData } = this.data;
		sendData.creditBeginDate = moment().format('YYYY-MM-DD');
		sendData.creditEndDate = moment().add('years', 1).format('YYYY-MM-DD');
	}

	// 跳企业详情
	_goDetail = () => {
		this.props.navigation.navigate('EnterpriseDetailsPage', {
			status: 'PASS',
			companyId: this.data.sendData.companyId,
			choice: this.choice
		})
	}

	//常用结算方式-初始化
	_accountsInit = async () => {
		let { typeData, lsAccountData } = this.data;
		let { corpTypeList } = this.data.sendData;
		corpTypeList && corpTypeList.forEach((item) => {
			if (item == '1') {
				//授信类型
				typeData.push({ dictKey: 'YF', dictName: '预付' });
			}
			else if (item == '2') {
				//授信类型
				typeData.push({ dictKey: 'SX', dictName: '赊销' });
			}
		})
		if (typeData && typeData.length == 1) {
			this.data.sendData.creditKind = typeData[0].dictKey;
			this.data.typeValue = typeData[0].dictName;
			if (typeData[0].dictKey == 'YF') {
				//结算方式
				lsAccountData && lsAccountData.forEach((itemData) => {
					if (itemData.dictKey == '2' || itemData.dictKey == '4') {
						this.data.accountData.push(itemData);
					}
				});
			} else if (typeData[0].dictKey == 'SX') {
				//结算方式
				lsAccountData && lsAccountData.forEach((itemData) => {
					if (itemData.dictKey == '3' || itemData.dictKey == '5') {
						this.data.accountData.push(itemData);
					}
				})
				//this._detailFn();
			}
		} else if (typeData.length == 2) {
			this.data.sendData.creditKind = typeData[0].dictKey;
			this.data.typeValue = typeData[0].dictName;
			this.data.accountData = lsAccountData;
		}
		this._detailFn();

		// 回显
		if (this.echoData) {
			let lsIndex = null;
			let typeIndex = null;
			let { creditKind, settlementType } = this.echoData;
			typeData.forEach((element, index) => {
				if (element.dictKey == creditKind) {
					lsIndex = index;
				}
			});
			(lsIndex || lsIndex == 0) && this._typeCallBack(lsIndex);
			this.data.accountData.forEach((element, index) => {
				if (element.dictKey == settlementType) {
					typeIndex = index;
				}
			});
			(typeIndex || typeIndex == 0) && this._accountCallBack(typeIndex);
		}
		this.setState({
			loadPage: false,
			loadStatus: 'data'
		})
		return new Promise((resolve, reject) => {
			resolve(true);
		})
	}


	//选择-授信类型
	_typeCallBack = (index) => {
		let { typeData, lsAccountData } = this.data;
		this.data.accountData = [];

		// 控制 授信类型
		this.data.typeModal = false;
		this.data.typeValue = typeData[index].dictName;
		this.data.typeIndex = index;
		this.data.sendData.creditKind = typeData[index].dictKey;

		// 抹掉之前的数据（结算方式）
		this.data.accountValue = '请选择';
		this.data.accountIndex = -1;
		this.data.sendData.settlementType = null;

		// 控制 结算方式
		if (typeData[index].dictKey == 'YF') {
			//结算方式
			lsAccountData && lsAccountData.forEach((itemData) => {
				if (itemData.dictKey == '2' || itemData.dictKey == '4') {
					this.data.accountData.push(itemData);
				}
			});
		} else if (typeData[index].dictKey == 'SX') {
			//结算方式
			lsAccountData && lsAccountData.forEach((itemData) => {
				if (itemData.dictKey == '3' || itemData.dictKey == '5') {
					this.data.accountData.push(itemData);
				}
			});

		}
		this._detailFn();
		this.setState({
			loadPage: false
		});
	}

	//选择-常用结算方式
	_accountCallBack = (index) => {
		let { accountData } = this.data;
		this.data.accountModal = false;
		this.data.accountValue = accountData[index].dictName;
		this.data.accountIndex = index;
		this.data.sendData.settlementType = accountData[index].dictKey;
		this.setState({
			loadPage: false
		})
	}

	// 关闭弹框
	_closeModal = (obj) => {
		for (key in obj) {
			this.data[key] = false;
		}
		this.setState({
			loadPage: false
		})
	}

	//打开模态框
	_selecOpen = (obj) => {
		let { typeData } = this.data;
		for (key in obj) {
			if (key == 'accountModal') {
				if (!this.data.sendData.creditKind) {
					ToastUtil.showWarning('请先选择授信类型');
					return
				}
			}
			this.data[key] = true;
			if (key == 'typeModal' && typeData.length == 1) {
				return
			}
		}
		this.setState({
			loadPage: false
		})
	}

	//金额-输入框
	_writeFn = (str1, str2, strZhi) => {
		this.data.sendData[strZhi] = str2;
	}

	//天数-输入框
	_writeDayFn = (str1, strZhi) => {
		this.data.sendData[strZhi] = str1;
	}

	// 必填验证
	_regFn = () => {
		let onOff = true;
		let { sendData } = this.data;

		//授信类型-验证
		if (!sendData.creditKind) {
			ToastUtil.showWarning('请选择授信类型');
			return false;
		}
		//中信保审 
		if (sendData.zxbApproveAmount && (sendData.zxbApproveAmount > 10000000)) {
			ToastUtil.showWarning('中信保审批额度过大(最大额度1000亿)');
			return false;
		}
		//本次申请额度
		if (!sendData.creditApplyAmount) {
			ToastUtil.showWarning('请输入本次申请额度');
			return false;
		}
		//最大值限制
		if (sendData.creditApplyAmount > 10000000) {
			ToastUtil.showWarning('本次申请额度过大(最大额度1000亿)');
			return false;
		}
		//授信天数
		if (!sendData.accountDay) {
			ToastUtil.showWarning('请输入授信天数');
			return false;
		}
		//当年交易额
		if (!sendData.dealAmount) {
			ToastUtil.showWarning('请输入当年交易额');
			return false;
		}
		//dealMaxAmount
		if (!sendData.dealMaxAmount) {
			ToastUtil.showWarning('请输入预计今年最大单笔交易额');
			return false;
		}
		if (sendData.creditApplyAmount <= 0) {
			ToastUtil.showWarning('本次申请额度必须大于0');
			return false;
		}
		if (sendData.dealProfit <= 0) {
			ToastUtil.showWarning('交易利润必须大于0');
			return false;
		}
		if (sendData.dealAmount <= 0) {
			ToastUtil.showWarning('当年交易额必须大于0');
			return false;
		}
		if (sendData.dealMaxAmount <= 0) {
			ToastUtil.showWarning('预计今年最大单笔交易额必须大于0');
			return false;
		}

		return onOff;
	}

	//设置时间
	_setTimeCallback = (date) => {
		this.data.sendData.creditEndDate = date;
		this.setState({
			loadPage: false
		})
	}

	// 返回上一个页面
	_goBack = () => {
		this.props.navigation.goBack();
		this.requesting = false;
	}

	//提交
	_submitFn = async () => {
		//CREDTI_APPLY_SUBMIT：提交
		//CREDTI_APPLY_SAVE : 保存
		if (this.requesting) return;
		let { sendData } = this.data;

		// 必填验证
		if (!this._regFn()) {
			return false;
		}


		if (sendData.zxbApproveAmount) {
			sendData.zxbApproveAmount = MethodUtil.countObj.multiply(sendData.zxbApproveAmount, 10000);
		}
		if (sendData.creditApplyAmount) {
			sendData.creditApplyAmount = MethodUtil.countObj.multiply(sendData.creditApplyAmount, 10000);
		}

		sendData.corpId = this.choice.corpId;
		let subData = {
			creditApplyVO: sendData,
			// submitStep: "CREDTI_APPLY_SUBMIT"
			submitStep: "CREDTI_APPLY_SAVE"
		}

		this.setState({
			loadStatus: 'loading'
		})
		this.requesting = true;
		let saveData = await HTTP.POST(API_GENERATE(API.CREDIT_CREATE), subData);
		if (saveData && saveData.creditApplyId) {
			// 成功
			ToastUtil.showSuccess('提交成功').then(() => {
				this._goBack();
			})
		} else {
			this.requesting = false;
			if (sendData.zxbApproveAmount) {
				sendData.zxbApproveAmount = MethodUtil.countObj.divide(sendData.zxbApproveAmount, 10000);
			}
			if (sendData.creditApplyAmount) {
				sendData.creditApplyAmount = MethodUtil.countObj.divide(sendData.creditApplyAmount, 10000);
			}
		}
		this.setState({
			loadStatus: 'data'
		});
	}

	// 判断申请是不是大于1000
	_judge = (a) => {
		let strNum = Number(this.data.sendData['creditApplyAmount']);
		if (strNum >= 1000) {
			Alert.alert(
				'',
				`本次申请授信金额${strNum}万元，是否确认？`,
				[
					{ text: 'OK', onPress: () => console.log('OK Pressed') },
				],
				{ cancelable: false }
			)
		}
	}

	render() {
		let { loadStatus } = this.state;
		let {
			typeModal, typeData, typeIndex, typeValue,
			accountModal, accountData, accountValue, accountIndex,
			sendData, registerFund, registerFundCurrency, createTime, companyName,
			limitDetailData
		} = this.data || {};
		let {
			zxbApproveAmount, creditApplyAmount, accountDay, dealProfit, dealMaxAmount,
			remark, dealAmount, settlementType, dealProduct, creditEndDate } = sendData || {};
		let { usedAmount, creditAmount, hasOverdue, dealYear } = limitDetailData || {};
		return (
			<View style={styles.container}>
				<TouchableOpacity activeOpacity={1} onPress={this._goDetail} style={styles.headBox}>
					<View>
						<Text style={[styles.title, styles.white]}>{companyName}</Text>
						<View style={styles.headText}>
							<Text style={[styles.headInfo, styles.white]}>成立时间：{createTime}</Text>
							<Text style={[styles.headInfo, styles.white]}>注册资本：{registerFund}万{CURRENCY.getUnit(registerFundCurrency).text}</Text>
						</View>
					</View>
					<Image style={styles.leftArrows} source={require('../../../../imgs/credit/leftArrows.png')} />
				</TouchableOpacity>
				<KeyboardAvoidingView style={styles.from} behavior={Platform.OS === 'ios' ? 'padding' : null} keyboardVerticalOffset={20}>
					<ScrollView keyboardShouldPersistTaps={'handled'}>
						<View style={styles.fromItemBox}>
							<FormItem type={typeData.length > 1 ? 'select' : 'text'} callBackFn={() => { this._selecOpen({ typeModal }) }} title={'授信类型'} value={typeValue} />
							<FormItem title={'中信保审批额度'} regulation={'thousands'} onChangeTextFn={(str1, str2) => { this._writeFn(str1, str2, 'zxbApproveAmount') }} placeholder={'0.00'} keyboardType={'numeric'} iconRightText={'￥'} value={zxbApproveAmount || ''} rightText={'万元'} rightColor={{ color: 'red' }} />
							<FormItem onBlurFn={this._judge} title={'本次申请额度'} regulation={'thousands'} onChangeTextFn={(str1, str2) => { this._writeFn(str1, str2, 'creditApplyAmount') }} keyboardType={'numeric'} placeholder={'0.00'} iconRightText={'￥'} value={creditApplyAmount || ''} rightText={'万元'} rightColor={{ color: 'red' }} />
							<FormItem title={'授信天数'} onChangeTextFn={(str1) => { this._writeDayFn(str1, 'accountDay') }} keyboardType={'numeric'} value={accountDay} rightText={'天'} />

							<View>
								<FormItem type={'select'} title={'授信有效期'} value={creditEndDate} />
								<DatePicker
									style={styles.fromTime}
									date={creditEndDate}
									mode="date"
									format="YYYY-MM-DD"
									minDate={new Date()}
									maxDate="2100-12-01"
									confirmBtnText="确认"
									cancelBtnText="取消"
									customStyles={{
										dateIcon: {
											opacity: 0,
											width: 0
										},
										dateInput: {
											borderWidth: 0
										}
									}}
									onDateChange={(date) => { this._setTimeCallback(date); }}
								/></View>
							<View style={styles.moreInfo}>
								<Text style={styles.moreInfoText}>申请时已用额度：¥{usedAmount || '0.00'}</Text>
								<Text style={styles.moreInfoText}>当前授信额度：¥{creditAmount || '0.00'}</Text>
								<Text style={styles.moreInfoText}>是否存在逾期记录：{hasOverdue ? '是' : '否'}</Text>
								<Text style={styles.moreInfoText}>与客户交易年限：{dealYear || '0'}年</Text>
							</View>
							<FormItem isChinese={true} title={'备注'} onChangeTextFn={(str1) => { this._writeDayFn(str1, 'remark') }} placeholder={'请输入'} value={remark} />
						</View>
						<View style={styles.fromItemBox}>
							<FormItem title={'当年交易额'} regulation={'thousands'} onChangeTextFn={(str1, str2) => { this._writeFn(str1, str2, 'dealAmount') }} keyboardType={'numeric'} placeholder={'0.00'} iconRightText={'￥'} value={dealAmount || ''} />
							<FormItem type={'select'} callBackFn={() => { this._selecOpen({ accountModal }) }} title={'常用结算方式'} value={accountValue} />{/* settlementType */}
							<FormItem title={'交易利润'} regulation={'thousands'} onChangeTextFn={(str1, str2) => { this._writeFn(str1, str2, 'dealProfit') }} keyboardType={'numeric'} placeholder={'0.00'} iconRightText={'￥'} value={dealProfit || ''} />
							<FormItem title={'预计今年最大单笔交易额'} regulation={'thousands'} onChangeTextFn={(str1, str2) => { this._writeFn(str1, str2, 'dealMaxAmount') }} keyboardType={'numeric'} placeholder={'0.00'} iconRightText={'￥'} value={dealMaxAmount || ''} />
						</View>
						<View style={styles.btnBox}>
							<TouchableOpacity style={styles.commit} onPress={() => { this._submitFn() }}>
								<Text style={styles.commitText}>提交</Text>
							</TouchableOpacity>
						</View>
					</ScrollView>

					<Common type="modal" demoData={(
						<Common type="listRadio" selectIndex={typeIndex} title="选择授信类型" listData={typeData} selectCallBack={this._typeCallBack} />
					)} isVisible={typeModal} closeCallballFn={() => { this._closeModal({ typeModal }) }} />

					<Common type="modal" demoData={(
						<Common type="listRadio" selectIndex={accountIndex} title="选择常用结算方式" listData={accountData} selectCallBack={this._accountCallBack} />
					)} isVisible={accountModal} closeCallballFn={() => { this._closeModal({ accountModal }) }} />
				</KeyboardAvoidingView>

				{
					loadStatus == 'loading' ? (
						<View style={{ position: 'absolute', height: '100%', width: '100%', top: 0 }}>
							<PageStatusIndex status={loadStatus} />
						</View>
					) : null
				}
			</View >
		)
	}
}
const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: style.color.bgGray
	},
	headBox: {
		flexDirection: 'row',
		justifyContent: 'space-between',
		alignItems: 'center',
		backgroundColor: style.color.themeColor,
		paddingLeft: 28 * scale,
		paddingRight: 14 * scale,
		paddingBottom: 28 * scale
	},
	title: {
		fontSize: 16 * scale,
		lineHeight: 22 * scale,
		marginBottom: 11 * scale
	},
	leftArrows: {
		height: 30 * scale,
		width: 30 * scale,
	},
	headInfo: {
		fontSize: 12 * scale,
	},
	white: {
		color: style.color.white
	},
	headText: {
		width: 290 * scale,
		flexDirection: 'row',
		justifyContent: 'space-between',
		alignItems: 'center',
	},
	from: {
		flex: 1,
	},
	fromItemBox: {
		backgroundColor: style.color.white,
		paddingLeft: 15 * scale,
		paddingRight: 15 * scale,
		marginBottom: 12 * scale
	},
	btnBox: {
		backgroundColor: style.color.white,
	},
	commit: {
		marginLeft: 15 * scale,
		marginRight: 15 * scale,
		height: 44 * scale,
		borderRadius: 44 * scale,
		backgroundColor: style.color.themeColor,
		marginTop: 15 * scale,
		marginBottom: 10 * scale,
		bottom: 0 * scale,
	},
	commitText: {
		lineHeight: 44 * scale,
		textAlign: 'center',
		fontSize: 18 * scale,
		color: style.color.white
	},
	moreInfo: {
		borderBottomWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderBottomColor: style.color.gray,
		paddingBottom: 5 * scale,
		paddingTop: 5 * scale,
	},
	moreInfoText: {
		color: '#FC5454',
		fontSize: 13 * scale,
		lineHeight: 28 * scale
	},
	fromTime: {
		width: 205 * scale,
		paddingVertical: 0,
		paddingTop: 0,
		marginTop: 0,
		opacity: 0,
		position: 'absolute',
		right: 0,
		top: 5 * scale
	},

})